package com.interauto.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;

/**
 * @author: Zejun.Xu
 * @date: 2018/3/12 9:38
 * @description:
 * @modified By:
 */
public class HttpUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * get请求
     * @return
     */
    public static String doGet(String url) {
        try {
            HttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());

                return strResult;
            }
        }
        catch (IOException e) {
            logger.error("doGet error:{}",e);
        }

        return null;
    }

    /**
     * post请求(用于key-value格式的参数)
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map params) throws Exception{

        BufferedReader in = null;
        try {
            // 定义HttpClient
            HttpClient client = new DefaultHttpClient();
            // 实例化HTTP方法
            HttpPost request = new HttpPost();
            request.setURI(new URI(url));

            //设置参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String value = String.valueOf(params.get(name));
                nvps.add(new BasicNameValuePair(name, value));

            }
            request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            HttpResponse response = client.execute(request);
            System.out.println(response.toString());
            int code = response.getStatusLine().getStatusCode();
            if(code == 200){    //请求成功
                in = new BufferedReader(new InputStreamReader(response.getEntity()
                        .getContent(),"utf-8"));
                StringBuilder sb = new StringBuilder("");
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }
//                in.close();
                return sb.toString();
            }
            else{   //
                System.out.println("状态码:"+code);
                return null;
            }
        }
        catch(Exception e){
            e.printStackTrace();
            return null;
        }finally {
            if (in != null){
                in.close();
            }
        }
    }

    /**
     * post请求（用于请求json格式的参数）
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, String params) {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                return jsonString;
            }
            else{
                logger.error("请求返回:"+state+"("+url+")");
            }
        }catch (Exception e){
            logger.error("过程失败！",e);
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("doPost error:{}",e);
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error("doPost error:{}",e);
            }
        }
        return null;
    }

    public static String doPostSSL(String apiUrl, Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).build();
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;
        String httpStr = null;

        try {
//            httpPost.setConfig(requestConfig);
            List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
                        .getValue().toString());
                pairList.add(pair);
            }
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return null;
            }
            httpStr = EntityUtils.toString(entity, "utf-8");
        } catch (Exception e) {
            logger.info(e.getMessage());
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    logger.info(e.getMessage());
                }
            }
        }
        return httpStr;
    }

    private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
        SSLConnectionSocketFactory sslsf = null;
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

                @Override
                public void verify(String host, SSLSocket ssl) throws IOException {
                }

                @Override
                public void verify(String host, X509Certificate cert) throws SSLException {
                }

                @Override
                public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
                }
            });
        } catch (GeneralSecurityException e) {
            logger.info(e.getMessage());
        }
        return sslsf;
    }

    private void testgogo() throws Exception{
        //String url = "https://gimtest-sammbo.sammbo.com:8440/subscribe/subscribe/message/sendMessageWithSignature";
        String url="https://sa-shanbu.geely.com/subscribe/subscribe/message/sendMessageWithSignature";
        Map<String,String> map = new TreeMap<>();
        map.put("source","MK-weld-qa");
        map.put("receiver_type","0");
        map.put("receiver","0250250,0248585");
        //map.put("organizationIds","");
        map.put("title","包子测试标题1");
        map.put("content","包子测试内容1");
        JSONObject obj = new JSONObject();
        obj.put("textType",false);
        obj.put("type","10002");
        //obj.put("content","包子测试哈哈");
        obj.put("createTime",String.valueOf(System.currentTimeMillis()));
        obj.put("remarkUrl","http://www.baidu.com");
        obj.put("remarkOpenPc","0");
        map.put("messageData",JSONObject.toJSONString(obj));
        String requestParams = com.alibaba.fastjson.JSONObject.toJSONString(map);
        System.out.println("入参字符串为:"+requestParams);
        String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANJpVdh+TgaGjcpM5kHsmY4iTxMFx4QDpd4nmdYL0JP5O792KAYbPpUG5+N88DuzSPo8PQfAHqyxah0sW2pEz5JISOurJTzMDbUjsc04SjoBnVYfBwYfoP9fz5DOCm7xN2yF9ORBqiCNZVVmACbtzEt1dH6Io902vL0k9hlEUDutAgMBAAECgYAbqzJYt7M29HasxZP5000V/bj8PWRRHdGv9vEpzn/tFXcf5D+7HdYK7s+LgKBumVLdZRJ5dHAUMXhMwcp7nPTWgHcCHTPP/UePreTgh9isucJS8ml9AjMN5mPJKTZjiqMkrBiwhRTd1YAcMvxZTZ1pjwGbMBuiiGtK8A5PEinEQQJBAPbdQKtk6A0Dk7hQcHN768ojoOaLpBBPePmbKN5vEMT3I93QYnODjaq0kiE2OAksRrWClExJKu/adyFKm1GscWUCQQDaMrxH/ybohX9sUHonzrRUnWSE7i5w/M14gzKddJwbiVHjVZ8KxITpwxH0gkaGUb1x2E2jWQOMhKleO+KxreCpAkBqd+gRQ5bVLgrCvmaRWAvMhWs6o1Uh97ScKnAI5uvblx8v5lTfrwglbHVtv32RbzgbxnKBKDlNcvJYOF4ebnoFAkBS+nZlvt+yD4qsy1IZL1+eyhg/AUFCELGnAeXOwVjYk/lDRf1sn92X9GownRZq4Ez2LXchBqn110F9p7KHNYO5AkEAg2hX5iNub91Z3ZnsbSCBhQ4OoSx4LIH6s+yGzYw8hyCjQNm4qdY/G6iSlDIoWuOLMhTxnTZkNm4Pb9xE0zIA/Q==";
        String verifySignature = RSAUtils.sign(requestParams.getBytes("UTF-8"), privateKey);
        map.put("verifySignature",verifySignature);
        String result = HttpUtil.doPost(url, map);
        System.out.println(result);
    }

    public static void main(String[] args) throws Exception {
        HttpUtil one=new HttpUtil();
        one.testgogo();
    }
}
